﻿using System;
using System.Web;
using Medianamik.Core.Sugar;
using System.Linq;

namespace Medianamik.Core.HttpHandlers
{
    public class TemplateHttpHandler : IHttpHandler
    {
        public void ProcessRequest(HttpContext context)
        {
            Guid propertyId;
            Guid templateId;
            Guid nodeId;

            if (StringHelper.IsGuid(context.Request["id"], out templateId))
            {
                var template = ConfigManager.Get<MedianamikTemplate>(templateId);

                if (template != null)
                {
                    BuildHtml(context, template.Content, String.Empty);
                }
            }
            else if (StringHelper.IsGuid(context.Request["propertyid"], out propertyId) &&
                StringHelper.IsGuid(context.Request["nodeid"], out nodeId))
            {
                var node = NodeManager.GetNode(nodeId);
                var revision = context.Request["revision"];
                object c;

                if (!revision.IsNullOrEmpty())
                {
                    c = node.GetNodeProperties(new DateTime(long.Parse(revision)))
                        .First(p => p.NodeTypePropertyID == propertyId).Value;
                }
                else
                {
                    c = node[context.Request["culture"]][propertyId].Value;
                }

                BuildHtml(context, c == null ? "" : c.ToString(),
                          String.IsNullOrEmpty(context.Request["removemargin"]) ?
                          String.Empty : " style=\"margin:0;\"");
            }
        }

        private static void BuildHtml(HttpContext context, string content, string bodyStyle)
        {
            string css = "";
            var htmlContent = "";

            if (content != null)
                htmlContent = content;

            if (!String.IsNullOrEmpty(context.Request["css"]))
                css = String
                    .Format("<link rel=\"stylesheet\" type=\"text/css\" media=\"all\" href=\"{0}\" />\n",
                    context.Request["css"]);

            context.Response.Write("<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\">\n"
                + " <html xmlns=\"http://www.w3.org/1999/xhtml\">\n"
                + " <head>\n"
                + " <meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\" />\n"
                + css
                + " </head>\n"
                + " <body" + bodyStyle + ">"
                + htmlContent
                + " </body>"
                + " </html>");
        }

        public bool IsReusable
        {
            get
            {
                return true;
            }
        }
    }
}